package com.xq.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.xq.base.ResponseResult;
import com.xq.entity.UserInfo;
import com.xq.mapper.BindCardMapper;
import com.xq.mapper.UserInfoMapper;
import com.xq.service.ExcelService;
import com.xq.utils.MD5Sign;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

//import com.xq.entity.UserInfo;

@Log4j2
@RestController
@CrossOrigin
public class SharedingController {

    @Autowired
    private BindCardMapper bindCardMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

  /* @Autowired
   private TbUserMapper tbUserMapper;


    @RequestMapping("/shareding/save")
   public ResponseResult save(){

        for (long i=1;i<=10;i++){
            TbUser user = new TbUser();
            user.setUserName("大宝"+i);
            user.setId(i);
            user.setMobile("15921484451");
            user.setCreateDate(new Date());
            tbUserMapper.insertSelective(user);
        }

        return ResponseResult.success();
    }

    @RequestMapping("/shareding/list")
    public ResponseResult<TbUser> list(){
        ResponseResult<TbUser> result = ResponseResult.success(tbUserMapper.selectByExample(null));
        return ResponseResult.success(tbUserMapper.selectByExample(null));
    }

    @RequestMapping("/shareding/list2")
    public ResponseResult list2(){
        Example example = new Example(TbUser.class);
        example.createCriteria().andGreaterThanOrEqualTo("age",18);
        return ResponseResult.success(tbUserMapper.selectByExample(example));
    }*/


   /* @RequestMapping("/shareding/list3")
    public ResponseResult list3(){

        List<BindCardExtVo> list = bindCardMapper.selectBanksByUserId(1L);
        userInfoMapper.selectByPrimaryKey(1L);
        return ResponseResult.success(list);
    }*/

   /* @RequestMapping("/shareding/list4")
    public ResponseResult list4(@RequestBody Map<String,String> map){
       // String token = request.getHeader("token");
        List<BindCardExtVo> list = bindCardMapper.selectBanksByUserId(1L);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1L);
        userInfo.setUserName("二宝");
       userInfoMapper.updateByPrimaryKeySelective(userInfo);


        //userInfoMapper.updateByPrimaryKey(userInfo);
        //userInfoMapper.selectByPrimaryKey(1L);
        return ResponseResult.success(list);
    }*/


    @RequestMapping("/shareding/list5")
    public ResponseResult list4(){
        UserInfo userInfo = new UserInfo();
        userInfo.setMobile("15921484451");
        userInfo.setUserName("用户名");
        userInfo.setUserCardId("122331");
        userInfoMapper.insertSelective(userInfo);
        System.out.println(JSON.toJSONString(userInfo));
        return ResponseResult.success("");
    }

    @RequestMapping("/shareding/update")
    public ResponseResult list5(){
        UserInfo userInfo = new UserInfo();
        userInfo.setMobile("15921484451");
        userInfo.setUserName("大宝4");
        userInfo.setUserCardId("1223314");
        userInfo.setId(1L);
        userInfoMapper.updateByPrimaryKeySelective(userInfo);

        return ResponseResult.success("");
    }

    @RequestMapping("/sendSms")
    public ResponseResult sendSms(String mobile,String sign){
        String str = mobile+"|"+"4ce9aff5b08efabc0138f7bc349caefa";
        String serverSign = MD5Sign.md5Encode(str);
        if(!serverSign.equals(sign)){
            return ResponseResult.error("签名不合法");
        }
        System.out.println("发送验证码成功");
        return ResponseResult.success();
    }


/*
    @RequestMapping(value="/exportList")
    public void exportList(HttpServletRequest request, HttpServletResponse response) {
        String title = "用户记录"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd") +".xls";
        List<UserInfo> list = userInfoMapper.selectByExample(null);
        try {
            String[] headers = new String[] {"用户名称","手机号","身份证号"};
            String[]  fieldNames = new String[] {"userName","mobile","userCardId"};
            ExcelUtil<UserInfo> excelUtil = new ExcelUtil<UserInfo>();
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(title.getBytes("UTF-8"), "ISO8859-1"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
            excelUtil.exportExcel(UserInfo.class, title, headers, fieldNames, list, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
//	        	PermissionsHelper.clear();
        }

    }*/


    @RequestMapping(value="/exportList2")
    public void exportList2(HttpServletRequest request, HttpServletResponse response) {
        String title = "用户记录"+ DateFormatUtils.format(new Date(),"yyyy-MM-dd") +".xls";
        List<UserInfo> list = userInfoMapper.selectByExample(null);
        try {
            ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getBigWriter();
            writer.addHeaderAlias("userName","用户名称");
            writer.addHeaderAlias("mobile","手机号");
            writer.addHeaderAlias("userCardId","身份证号");
            writer.setOnlyAlias(true);
            writer.write(list, true);
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(title.getBytes("UTF-8"), "ISO8859-1"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
            writer.flush(response.getOutputStream(),true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
//	        	PermissionsHelper.clear();
        }

    }


    @RequestMapping(value="/importExcel")
    public void importExcel(MultipartFile file) {

        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> read = reader.read(1);
            System.out.println(JSON.toJSONString(read));
            for(List<Object> list : read){
                Date date = (Date)list.get(0);
                String task = (String)list.get(1);
                //Long finish = (Long)list.get(2);
                System.out.println(DateFormatUtils.format(date,"yyyy-MM-dd") +" "+task+" ");
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }


   /* @RequestMapping(value="/importExcel")
    public void importExcel(MultipartFile file) {



        try {
            List<String[]> userList = ExcelExport.readExcel(file);

            System.out.println(JSON.toJSONString(userList));
           *//* List<List<Object>> read = ExceUtils.readExcel(file.getInputStream());
            System.out.println(JSON.toJSONString(read));*//*
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }*/

    @RequestMapping(value="/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        try {
            List<UserInfo> list = Lists.newArrayList();
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName("大宝");
            userInfo.setMobile("15921484451");
            userInfo.setId(1L);
            list.add(userInfo);
            UserInfo userInfo2 = new UserInfo();
            userInfo2.setUserName("大宝2");
            userInfo2.setMobile("15921484452");
            list.add(userInfo2);
            userInfo.setId(2L);

           /* ExcelExport excelExport = new ExcelExport(response, "用户数据", "sheet1");
            excelExport.writeExcel(new String[]{"userName", "mobile","id"},new String[]{"CUSTOMER_NUMBER", "TEX_INCLOUD","ID"}
                    , new String[]{"合同编号", "含税","ID"}
                    , new int[]{30, 30,30}, list);*/

            //listString title="文件名称.xlsx";
            //InputStream inputStream = this.getClass().getResourceAsStream("/模板2.xlsx");
           /* PoiExcelUtil excelUtil = new PoiExcelUtil("2007");
            List<List<String>> list = Lists.newArrayList();
            List<String> aList = Lists.newArrayList();
            aList.add("1");
            aList.add("2");
            list.add(aList);
            excelUtil.write(list,"sheet1",true);
            excelUtil.getWorkbook().write(response.getOutputStream());*/
           /* response.setHeader("Content-Disposition", "attachment;fileName=" + new String(title.getBytes("UTF-8"), "ISO8859-1"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");*/
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }



    @RequestMapping(value="/getExcel")
    public void getExcel(HttpServletResponse response) {
        try {

            InputStream inputStream = this.getClass().getResourceAsStream("/上海终身教育学分银行证书网点基本信息登记表.xlsx");
            //假如以中文名下载的话，设置下载文件名称
            String filename = "导出信息.xls";
            //转码，免得文件名中文乱码
            filename = URLEncoder.encode(filename,"UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int b = 0;
            byte[] buffer = new byte[1024];
            while ((b = inputStream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, b);
            }
            inputStream.close();

            if (out != null) {
            out.flush();
            out.close();
            }
        } catch (Exception ex) {
            log.error("getApplicationTemplate :", ex);
        }
    }

    @Autowired
    private ExcelService excelService;

    @RequestMapping(value="/excel")
    public void excel(HttpServletResponse response) {
        try {

            InputStream inputStream = this.getClass().getResourceAsStream("/上海终身教育学分银行证书网点基本信息登记表.xlsx");
            //假如以中文名下载的话，设置下载文件名称
            String filename = "导出信息.xls";
            //转码，免得文件名中文乱码
            filename = URLEncoder.encode(filename,"UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            excelService.excel(inputStream,response);

        } catch (Exception ex) {
            log.error("getApplicationTemplate :", ex);
        }
    }

    @RequestMapping(value="/mobile")
    public void sendSMS(String mobile,String sign){
        //15921484451，c89218cebe5a2d82a58d1ee276ab51c243242343243
        //加密签名
        String secrit="c89218cebe5a2d82a58d1ee276ab51c7";
        String serviceSign = MD5Sign.md5Encode(mobile+"|"+secrit);
        if(!sign.equals(serviceSign)){
            return;
        }
        System.out.println("发送短信验证码成功");
        return;
    }




   /* @RequestMapping(value="/mobile")
    public void sendSMS(String mobile,String sign){
        String secrit="c89218cebe5a2d82a58d1ee276ab51c7";
        String serviceSign = MD5Sign.md5Encode(mobile+"|"+secrit);
        if(!sign.equals(serviceSign)){
            return;
        }
        System.out.println("发送短信验证码成功");
        return;
    }*/





}
